package com.itcm.skymail.cart.interceptor;

import com.itcm.common.constant.AuthServerConstant;
import com.itcm.common.constant.CartConstant;
import com.itcm.common.vo.ResultMemberVo;
import com.itcm.skymail.cart.to.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 描述: 执行目标方法之前 判断用户登录状态 以及未登录时判断cookie是否包含user-key:用户唯一标识
 * 并封装用户信息 传递给controller
 * <p>
 * 拦截器要生效 必须要在webConfig中配置 -- SkymallWebConfig
 *
 * @author cm_fighting
 * @create 2020-11-23 10:31 上午
 */
@Slf4j
public class CartInterceptor implements HandlerInterceptor {

    // ThreadLocal 用于同一线程共享数据
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /*
     * 目标方法执行之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserInfoTo userInfoTo = new UserInfoTo();
        ResultMemberVo memberVo = (ResultMemberVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberVo == null) {
            // 用户未登录
            log.info("用户未登录");
        } else {
            // 已登录
            userInfoTo.setUserId(memberVo.getId());
        }
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                userInfoTo.setUserKey(cookie.getValue());
                userInfoTo.setTempUser(true);
            }
        }
        // 若第一次访问 要为浏览器cookie中创建一个用户标识（本项目中采用uuid）保存在user-key中
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

        // 将封装好的用户信息放入threadLocal中
        threadLocal.set(userInfoTo);
        return true;
    }

    /*
     * 目标方法执行之后
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setMaxAge(30 * 24 * 60 * 60);
            cookie.setDomain("skymail.com");
            response.addCookie(cookie);
        }
    }
    // afterCompletion ： DispatcherServlet进行视图的渲染之后，多用于清理资源
}
